package cn.fotoit.product.system.controller;


import cn.fotoit.product.system.entity.Permission;
import cn.fotoit.product.system.entity.Role;
import cn.fotoit.product.system.entity.RoleRelPermission;
import cn.fotoit.product.system.entity.User;
import cn.fotoit.product.system.service.PermissionService;
import cn.fotoit.product.system.service.RoleRelPermissionService;
import cn.fotoit.product.system.service.RoleService;
import cn.fotoit.product.system.service.UserService;
import cn.fotoit.product.util.LogInfo;
import cn.fotoit.product.util.PasswordUtil;
import cn.fotoit.product.util.ReturnBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Api(value = "公共接口", tags = "系统公共接口，登陆，退出，修改密码，获取用户当前信息，修改昵称，检查登陆名")
@RestController
@CrossOrigin
@Slf4j
public class PublicController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRelPermissionService roleRelPermissionService;

    @Autowired
    private PermissionService permissionService;


    @LogInfo(info = "用户登陆", saveResponseData = true)
    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public ReturnBean login(
            @RequestParam String loginName,
            @RequestParam String loginPassword,
            @RequestParam(required = false, defaultValue = "false") Boolean rememberMe) {

        UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPassword);
        token.setRememberMe(rememberMe);
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.login(token);
        if (currentUser.isAuthenticated()) {//认证通过
            User byLoginName = userService.findByLoginName(loginName);
            log.info("用户[" + loginName + "]登录认证通过");
            return ReturnBean.success("登陆成功", byLoginName);
        }
        return ReturnBean.error("认证未通过");
    }


    @LogInfo(info = "用户退出")
    @PostMapping("logout")
    public ReturnBean logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isRemembered() || subject.isAuthenticated()) {
            log.info("用户:{} 注销成功", subject.getPrincipal());
            subject.logout();
            return ReturnBean.success("注销成功");
        } else {
            return ReturnBean.error("用户已经注销");
        }
    }


    @LogInfo(info = "修改用户自己的密码")
    @PostMapping("updatePassword")
    public ReturnBean updatePassword(@RequestParam String newPassword, @RequestParam String oldPassword) {
        if (newPassword.length() < 3) {
            return ReturnBean.error("新密码长度不足");
        }
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Integer userId = (Integer) subject.getPrincipal();
            User user = userService.findById(userId);
            if (user.getLoginPassword().equals(PasswordUtil.getPasswordByUsernameAndPassword(user.getLoginName(), oldPassword))) {
                user.setLoginPassword(PasswordUtil.getPasswordByUsernameAndPassword(user.getLoginName(), newPassword));
                userService.updateNotNull(user);
                return ReturnBean.success("修改成功");
            }
            return ReturnBean.error("输入原密码错误");


        }
        return ReturnBean.error("没有访问该资源的权限，请联系管理员");
    }


    @LogInfo(info = "获取当前登陆的用户信息")
    @PostMapping("getMyRole")
    public ReturnBean getMyRole() {
        Subject currentUser = SecurityUtils.getSubject();
        //获取用户信息可以通过记住我或者直接登录获取
        if (currentUser.isRemembered() || currentUser.isAuthenticated()) {
            Integer userId = (Integer) currentUser.getPrincipal();
            User user = userService.findById(userId);
            Role role = roleService.findById(user.getRoleId());
            return ReturnBean.success("查询成功", role);
        }
        return ReturnBean.error("没有访问该资源的权限，请联系管理员");
    }

    @LogInfo(info = "获取当前登陆的用户信息")
    @PostMapping("getMyPermission")
    public ReturnBean getMyPermission() {
        Subject currentUser = SecurityUtils.getSubject();
        //获取用户信息可以通过记住我或者直接登录获取
        if (currentUser.isRemembered() || currentUser.isAuthenticated()) {
            Integer userId = (Integer) currentUser.getPrincipal();
            User user = userService.findById(userId);
            List<RoleRelPermission> byRoleId = roleRelPermissionService.findByRoleId(user.getRoleId());
            List<Integer> pIds = new ArrayList<>();
            for (RoleRelPermission roleRelPermission : byRoleId) {
                pIds.add(roleRelPermission.getPermissionId());
            }
            List<Permission> byIdIn = permissionService.findByIdIn(pIds);
            return ReturnBean.success("查询成功", byIdIn);
        }
        return ReturnBean.error("没有访问该资源的权限，请联系管理员");
    }

    @LogInfo(info = "修改用户昵称", saveResponseData = true, saveRequestData = true)
    @PostMapping("changeNickName")
    public ReturnBean changeUserName(@RequestParam String nickName) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Integer userId = (Integer) currentUser.getPrincipal();
            User user = userService.findById(userId);
            user.setNickName(nickName);
            userService.updateNotNull(user);
            return ReturnBean.success("修改成功");
        }
        return ReturnBean.error("没有访问该资源的权限，请联系管理员");

    }

    @LogInfo(info = "检查登陆名是否存在", saveRequestData = true, saveResponseData = true)
    @PostMapping("checkLoginName")
    public ReturnBean checkLoginName(@RequestParam String loginName) {

        Boolean has = userService.checkLoginName(loginName);
        if (has) {
            return ReturnBean.success("可以添加");
        }
        return ReturnBean.error("用户存在");
    }


}
